package com.qilu.pe.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.Clinic;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.JsonBean;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GetJsonDataUtil;
import com.qilu.pe.support.util.PeUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;

import org.json.JSONArray;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的诊所
public class MyClinicActivity extends Base2Activity {
    private RecyclerView rcv_list;// 成员列表
    private TextView tv_coupon;// 运费券
    private TextView et_agent_name, et_type_name, et_licence, et_charge;
    private TextView et_charge_phone, et_addr, et_time;
    private TextView tv_addr, tv_add_member, tv_pay_detail;
    private LinearLayout ll_addr;

    private MemberListAdapter adapter;
    private List<Doctor> doctorList = new ArrayList<>();

    private Clinic clinic;// 请求得到的我的诊所对象

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_my_clinic;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        rcv_list = findViewById(R.id.rcv_list);
        tv_coupon = findViewById(R.id.tv_coupon);
        et_agent_name = findViewById(R.id.et_agent_name);
        et_type_name = findViewById(R.id.et_type_name);
        et_licence = findViewById(R.id.et_licence);
        et_charge = findViewById(R.id.et_charge);
        et_charge_phone = findViewById(R.id.et_charge_phone);
        et_addr = findViewById(R.id.et_addr);
        et_time = findViewById(R.id.et_time);
        tv_addr = findViewById(R.id.tv_addr);
        tv_add_member = findViewById(R.id.tv_add_member);
        tv_pay_detail = findViewById(R.id.tv_pay_detail);
        ll_addr = findViewById(R.id.ll_addr);

        setHeadTitle("我的诊所");

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new MemberListAdapter(this);
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);

        setListeners();

        hideProgress();
        reqMyClinic();
        showProgress();
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqMyClinicDoctorList();
    }

    private void setListeners() {
        setOnClickListener(tv_coupon, tv_add_member, tv_pay_detail, ll_addr);
    }

    // 请求我的诊所
    private Disposable reqMyClinic() {
        return APIRetrofit.getDefault().reqMyClinic(Global.HEADER, Global.ORG_ID)
                .compose(RxUtil.<BaseResult2<Clinic>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<Clinic>>() {
                    @Override
                    public void accept(BaseResult2<Clinic> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {

                        } else {

                        }
                        clinic = result2.getData();
                        setViewData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 我的诊所医生
    private Disposable reqMyClinicDoctorList() {
        return APIRetrofit.getDefault().reqMyClinicDoctorList(Global.HEADER, Global.ORG_ID)
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> listResult2) throws Exception {
                        hideProgress();
                        if (listResult2.isSuccess()) {

                        } else {

                        }
                        doctorList = listResult2.getData();
                        adapter.setDataList(doctorList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 请求删除医生
    private Disposable reqDelDoctor(String doctorId) {
        return APIRetrofit.getDefault().reqDelDoctor(Global.HEADER, doctorId)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {

                        } else {

                        }
                        reqMyClinicDoctorList();// 删除完成,重新请求医生列表
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private void setViewData() {
        et_agent_name.setText(clinic.getName());
        // 1 综合性医院 2 社区卫生服务中心 3 门诊部/诊所/卫生所/医务室/村卫生室 4 采供血机构
        et_type_name.setText(PeUtil.getAgentTypeName(clinic.getType()));
        et_agent_name.setText(clinic.getName());
        et_licence.setText(clinic.getLicence());
        et_charge.setText(clinic.getUsername());
        et_charge_phone.setText(clinic.getPhone());
        tv_addr.setText(clinic.getArea());
        et_addr.setText(clinic.getAddress());
        et_time.setText(clinic.getCreated_at());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_coupon) {// 运费券
            startActivity(CouponTransActivity.class);
        }
        if (v == tv_add_member) {
            startActivity(AddDoctorActivity.class);
        }
        if (v == ll_addr) {
//            initJsonData();
//            ShowPickerView();
        }
        if (v == tv_pay_detail) {// 机构流水
            Bundle bundle = new Bundle();
            bundle.putSerializable("doctorList", (Serializable) doctorList);
            startActivity(AgentFlowActivity.class, bundle);
        }
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据
//         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
//         * 关键逻辑在于循环体
        String JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

//         * 添加省份数据
//         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
//         * PickerView会通过getPickerViewText方法获取字符串显示出来。
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getAreaList() == null || jsonBean.get(i).getCityList().get(c).getAreaList().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getAreaList().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getAreaList().get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            //添加城市数据
            options2Items.add(CityList);
            //添加地区数据
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ? options1Items.get(options1).getPickerViewText() : "";
                String opt2tx = options2Items.size() > 0 && options2Items.get(options1).size() > 0 ? options2Items.get(options1).get(options2) : "";
                String opt3tx = options2Items.size() > 0 && options3Items.get(options1).size() > 0 && options3Items.get(options1).get(options2).size() > 0 ? options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                ToastUtils.showShort(tx);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
        ToastUtils.showShort("选择地址");
    }

    private class MemberListAdapter extends ListBaseAdapter<Doctor> {

        public MemberListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_my_clinic_member_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_rank = holder.getView(R.id.tv_rank);
            TextView tv_edit = holder.getView(R.id.tv_edit);
            TextView tv_del = holder.getView(R.id.tv_del);

            final Doctor doctor = mDataList.get(position);

            tv_name.setText(doctor.getName());

            tv_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MyClinicActivity.this, AddDoctorActivity.class)
                            .putExtra("id", doctor.getId())
                    );
                }
            });
            tv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = "是否删除该医生?";
                    AlertUtil.showComDialog(MyClinicActivity.this, msg, new AlertUtil.OnAlertBtnClickListner() {
                        @Override
                        public void onConfirmClick() {
                            hideProgress();
                            reqDelDoctor(doctor.getId());
                            showProgress();
                        }

                        @Override
                        public void onCancelClick() {
//                            ToastUtils.showShort("取消");
                        }
                    });
                }
            });
        }
    }
}